package cn.bugDance.aop;

import cn.bugDance.domain.security.servive.shiro.JwtUtil;
import cn.bugDance.types.annotations.LoginRequire;
import cn.bugDance.types.enums.ResponseCode;
import cn.bugDance.types.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class CheckLoginAop {


    @Pointcut("@annotation(cn.bugDance.types.annotations.LoginRequire)")
    public void aopPoint(){}

    @Around("aopPoint()")
    public Object check(ProceedingJoinPoint jp) throws Throwable {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        LoginRequire loginRequire = signature.getMethod().getAnnotation(LoginRequire.class);
        if(!loginRequire.required()) return jp.proceed();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader(loginRequire.value());
        if(StringUtils.isBlank(token)){
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo()).build();
        }
        JwtUtil jwtUtil = new JwtUtil();
        if(!jwtUtil.isVerify(token)){
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo()).build();
        }
        return jp.proceed();
    }
}
